#

| Chapter 13 Redirecting Input and Output |

## 13.6 Safe I/O Redirection with noclobber

Have you ever destroyed a file accidentally? If you set the noclobber C shell variable, or the noclobber option in bash and ksh, it can help you avoid these mistakes. Setting noclobber prevents you from destroying a file when you are redirecting standard output (13.1).

Consider the following situation:

>     % anycommand > outputfile

The command above destroys the old outputfile and creates a new one. If you have misspelled the name of your output file, or if you have forgotten that the file already exists and contains important data, or (most common) if you really meant to type `>>` instead of `>` (i.e., if you really meant to append to the end of outputfile, rather than start a new one), tough luck; your old data is gone.

Setting the variable noclobber prevents this problem. If noclobber exists, the C shell will not allow I/O redirection to destroy an existing file, unless you explicitly tell it to by adding an exclamation point (`!`) after the C shell redirect symbol - or a vertical bar (`|`) in ksh and bash. Here are examples. The left column shows csh and tcsh; the right column is for bash (ksh is similar):

>     % set noclobber             $ set -o noclobber
>     % ls                         $ ls
>     filea fileb                filea fileb
>     % anyprogram > fileb       $ anyprogram > fileb
>     fileb: File exists.        bash: fileb: Cannot clobber existing file
>     % anyprogram >! fileb      $ anyprogram >| fileb
>     %                            $

Be sure to put space after the `!`. If you don't, the C shell thinks you're making a history reference and it (usually) prints an error like `fileb: Event not found.`

Remember that noclobber is not an environment variable, so any new shells you create won't inherit it (6.8). Therefore, if you want this feature, put the set command (above) in your shell's setup file (2.2).

> NOTE: In some C shells, noclobber will prevent you from redirecting standard output to /dev/null (13.14) or to a terminal unless you add the `!`.

The C shell noclobber variable has one other feature that's worth noting. Normally, the C shell lets you append to a file that doesn't exist. If noclobber is set under csh and tcsh, it won't; you can only append to files that already exist unless you use an exclamation point:

>     % ls
>     filea fileb
>     % anyprogram >> filec
>     filec: No such file or directory
>     % anyprogram >>! filec
>     %

- ML, JP

13.5 Redirection in C Shell: Capture Errors, Too? |  | 13.7 The () Subshell Operators